package cn.org.mrliu.code.generator.util;

import java.io.File;
import java.io.IOException;

import cn.org.mrliu.code.generator.config.ConfigUtil;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;

public class ConfigurationUtil {
	private static String FTL_ENCODING = "UTF-8";
	private static Configuration cfg;

	static {
		cfg = new Configuration(Configuration.VERSION_2_3_22);
	}

	public static Configuration getConfiguration() {
		String templateDir = ConfigUtil.getConfig().getTemplateDir();
		if (templateDir == null || templateDir.trim().length() == 0) {
			throw new RuntimeException("请配置模板目录");
		}
		return getConfiguration(templateDir);
	}

	public static Configuration getConfiguration(String templateDir) {
		return getConfiguration(templateDir, FTL_ENCODING);
	}

	public static Configuration getConfiguration(String templateDir, String templateEncoding) {
		File file = new File(templateDir);
		try {
			cfg.setDirectoryForTemplateLoading(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		cfg.setDefaultEncoding(templateEncoding);
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		return cfg;
	}
}
